package com.shanghaionstar.servicepackage;

import android.content.Intent;
import android.graphics.Paint;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.more.entity.PackageInfo;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.OrderPayActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.servicepackage.adapter.OnstarChoosePkgAdapter;
import com.shanghaionstar.servicepackage.presenter.OnstarBuyPkgPresenter;
import com.shanghaionstar.servicepackage.view.OnstarBuyPkgView;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.user.renew.CurrentDataPackageActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.WebViewSettingUtil;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 安吉星套餐列表页
 */
@ContentView(R.layout.onstar_payme_activity_service_order)
public class OnstarBuyPackageActivity extends SwipeActivity implements View.OnClickListener, OnstarChoosePkgAdapter.EbCallBackListener, OnstarBuyPkgView {
    private boolean hasDegreeCodeZero = false;
    private boolean hasDegreeCodeOne = false;
    private boolean hasDegreeCodeTwo = false;
    private String degreeCodeZeroDesc;
    private String degreeCodeOneDesc;
    private String degreeCodeTwoDesc;
    private static final String TAG = OnstarBuyPackageActivity.class.getSimpleName();
    @FindViewById
    private TextView no_current_package;
    @FindViewById
    private ImageView tab_3;
    @FindViewById
    LinearLayout core_ll, data_ll,eb_layout_rule;
    @FindViewById
    private Button buy_now_btn;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private ProgressLayout package_list_progress;
    @FindViewById
    private TextView tab_0, tab_1, tab_2, tv_no_package, tv_CMCC;
    @FindViewById
    private TextView no_payme_list_data;
    @FindViewById
    private TextView package_name, start_date, end_date, actual_price, offer_desc, package_price, description, package_layout, duration, duration_unit;
    @FindViewById
    private GridView elv_order_select;
    private OnstarChoosePkgAdapter adpter;
    private List<PackageInfo> groupList;
    private List<PackageInfo> childList;
    private PackageType packageType;
    @FindViewById(background = R.drawable.onstar_join_me_bg)
    private RelativeLayout layout_background;
    @FindViewById
    private WebView webview_rule;
    private boolean isEBPackage = false;
    @FindViewById
    private TextView package_name_eb;

    @FindViewById
    private RelativeLayout parent_layout;

    private OnstarBuyPkgPresenter packagePresenter;

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        getPackageType();
        setUpViews();
        loadPackageInfos();
    }

    /**
     * 异步加载套餐数据
     */
    private void loadPackageInfos() {
        getPackagePresenter().getOnstarPackages(packageType);
    }

    private void getPackageType() {
        packageType = PackageType.DATA;
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            packageType = (PackageType) bundle.getSerializable("packageType");
            String from = bundle.getString("from");
            if(TextUtils.isEmpty(from))
                tab_3.setVisibility(View.GONE);
        }
    }

    private void setUpViews() {
        if (packageType.equals(PackageType.CORE)) {
            top_layout.setTopTitle(getString(R.string.core));
            core_ll.setVisibility(View.VISIBLE);
        } else {
            tv_CMCC.setVisibility(View.GONE);
            data_ll.setVisibility(View.VISIBLE);
            top_layout.setTopTitle(getString(R.string.data));
        }
        package_list_progress.setVisibility(View.VISIBLE);
        package_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        package_layout.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        no_payme_list_data.setVisibility(View.GONE);

        setUpWebView();
    }

    private void setUpWebView() {
        String url = Constants.CURRENT_PREFIX_H5_URL + Constants.EB_CONDITION_URL;
        WebViewSettingUtil.setupDefaultSettings(webview_rule);
        webview_rule.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                handler.proceed();
            }
        });
        webview_rule.loadUrl(url);
    }

    public OnstarBuyPkgPresenter getPackagePresenter() {
        if (packagePresenter == null) {
            packagePresenter = new OnstarBuyPkgPresenter(getScheduler(), this);
            packagePresenter.setPackageView(this);
        }
        return packagePresenter;
    }

    /**
     * 显示套餐数据
     *
     * @param infoList
     */
    @Override
    public void showPackageInfos(List<PackageInfo> infoList) {
        buy_now_btn.setVisibility(View.VISIBLE);
        package_list_progress.setVisibility(View.GONE);
        groupList = infoList;
        if (childList == null)
            childList = new ArrayList<>();
        childList.clear();
        initTabs();
    }

    @Override
    public void showErr(Throwable throwable) {
        package_list_progress.setVisibility(View.GONE);
        parent_layout.setVisibility(View.GONE);
        no_current_package.setVisibility(View.VISIBLE);
        no_current_package.setText(getResources().getString(R.string.no_payme_list_datas_error));
        if (throwable instanceof HttpException)
            AlertDialogUtil.showDialogByExceptionCode(OnstarBuyPackageActivity.this, (HttpException) throwable);
    }

    private void initTabs() {
        adpter = new OnstarChoosePkgAdapter(childList, this, this);
        hasDegreeCodeZero = false;
        hasDegreeCodeOne = false;
        hasDegreeCodeTwo = false;
        if (groupList != null && groupList.size() > 0) {
            for (PackageInfo packageInfo : groupList) {
                if (!hasDegreeCodeZero && "0".equals(packageInfo.getDegreeCode())) {
                    hasDegreeCodeZero = true;
                    degreeCodeZeroDesc = packageInfo.getDegreeDesc();
                } else if (!hasDegreeCodeOne && "1".equals(packageInfo.getDegreeCode())) {
                    hasDegreeCodeOne = true;
                    degreeCodeOneDesc = packageInfo.getDegreeDesc();
                } else if (!hasDegreeCodeTwo && "2".equals(packageInfo.getDegreeCode())) {
                    hasDegreeCodeTwo = true;
                    degreeCodeTwoDesc = packageInfo.getDegreeDesc();
                }
            }
            if (hasDegreeCodeTwo) {
                adpter.setDegreeCode("2");
                tab_2.setVisibility(View.VISIBLE);
                tab_2.setText(degreeCodeTwoDesc);
            } else {
                tab_2.setEnabled(false);
                tab_2.setVisibility(View.GONE);
                adpter.setDegreeCode("empty_code");
            }
            if (hasDegreeCodeOne) {
                adpter.setDegreeCode("1");
                tab_1.setVisibility(View.VISIBLE);
                tab_1.setText(degreeCodeOneDesc);
            } else {
                tab_1.setEnabled(false);
                tab_1.setVisibility(View.GONE);
            }
            if (hasDegreeCodeZero) {
                tab_0.setVisibility(View.VISIBLE);
                tab_0.setText(degreeCodeZeroDesc);
                adpter.setDegreeCode("0");
            } else {
                tab_0.setEnabled(false);
                tab_0.setVisibility(View.GONE);
            }
            elv_order_select.setAdapter(adpter);
            no_current_package.setVisibility(View.GONE);

            if (CommonUtil.isNull(adpter.getDegreeCode()))
                adpter.setDegreeCode("empty_code");//表示没有数据

            if (adpter.getDegreeCode().equals("0")) {
                tab_0.performClick();
            } else if (adpter.getDegreeCode().equals("1")) {
                tab_1.performClick();
            } else if (adpter.getDegreeCode().equals("2")) {
                tab_2.performClick();
            } else {
                parent_layout.setVisibility(View.GONE);
                no_current_package.setVisibility(View.VISIBLE);
            }
        } else {
            parent_layout.setVisibility(View.GONE);
            no_current_package.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.buy_now_btn, R.id.tab_0, R.id.tab_1, R.id.tab_2,R.id.tab_3})
    @Override
    public void onClick(View arg0) {
        if (groupList == null || groupList.size() == 0)
            return;
        switch (arg0.getId()) {
            case R.id.buy_now_btn://选择套餐-下一步按钮
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_buynow.getStringValue());

                onClickBuyNow();
                break;
            case R.id.tab_0://第一个tab
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_hotsale.getStringValue());
                onClickTabOne();
                break;
            case R.id.tab_1://第二个tab
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_oneyear.getStringValue());

                onClickTabTwo();
                break;
            case R.id.tab_2://第三个tab
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_twoyears.getStringValue());

                onClickTabThree();
                break;
            case R.id.tab_3://第三个tab

                jumpToData();
                break;
        }
    }

    private void jumpToData() {
        Intent it = new Intent(OnstarBuyPackageActivity.this, CurrentDataPackageActivity.class);
        startActivity(it);
    }

    private void onClickBuyNow() {
        if (adpter != null && adpter.getSelectPackInfo() != null) {
//            BusinessUtil.sendReportByClickType(
//                    OnstarBuyPackageActivity.this,
//                    packageType == PackageType.DATA ?
//                            FunctionNameFindId.Data_Plan_Create_Order_Button.getStringValue() :
//                            FunctionNameFindId.Payme_create_order.getStringValue());
            Intent intent = new Intent(this, OrderPayActivity.class);
            intent.putExtra(OrderPayActivity.PACKAGE_TYPE, packageType);
            intent.putExtra("isEBPackage", isEBPackage);
            intent.putExtra(OrderPayActivity.PACKAGE_NAME,adpter.getSelectPackInfo().getPackageName());
            intent.putExtra(OrderPayActivity.PACKAGE_PRICE, adpter.getSelectPackInfo().getActualPrice()+"");
            intent.putExtra(OrderPayActivity.PACKAGE_ID, adpter.getSelectPackInfo().getPackageId());
            startActivity(intent);
        } else {
            AlertDialogUtil.showAlertDialog(OnstarBuyPackageActivity.this, R.string.dialog_warning,
                    R.string.SB027_MSG013);
        }
    }

    private void onClickTabOne() {
        if (childList == null)
            childList = new ArrayList<>();
        childList.clear();
        for (PackageInfo entity : groupList) {
            if (!CommonUtil.isNull(entity.getDegreeCode()) && "0".equals(entity.getDegreeCode())) {
                tv_no_package.setVisibility(View.GONE);//没有流量提醒清除yqt
                childList.add(entity);
            } else {//添加没有流量包提醒
                if (Constants.PACKAGE_HOT.equals(entity.getDegreeCode()))
                    tv_no_package.setVisibility(View.VISIBLE);
            }
        }
        if (childList != null && childList.size() > 0) {
            adpter.setGroupList(childList);
            adpter.setSelectPackInfo(childList.get(0));
            adpter.setPosition(0);
            adpter.setSelectPosition(0);
            adpter.setDegreeCode("0");
            adpter.notifyDataSetChanged();
            tab_0.setTextColor(ContextCompat.getColor(this, R.color.font_flow_price));
            tab_1.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_2.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_0.setBackgroundResource(R.drawable.img_tab);
            tab_1.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
            tab_2.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
        }
    }

    private void onClickTabTwo() {
        if (childList == null)
            childList = new ArrayList<>();
        childList.clear();
        for (PackageInfo entity : groupList) {
            if (!CommonUtil.isNull(entity.getDegreeCode()) && (entity.getDegreeCode().equals("1"))) {
                tv_no_package.setVisibility(View.GONE);
                childList.add(entity);
            } else {  //添加没有流量包提醒
                if (Constants.PACKAGE_ONE_YEAR.equals(entity.getDegreeCode()))
                    tv_no_package.setVisibility(View.VISIBLE);
            }
        }
        if (childList != null && childList.size() > 0) {
            adpter.setDegreeCode("1");
            adpter.setSelectPackInfo(childList.get(0));
            adpter.setPosition(0);
            adpter.setSelectPosition(0);
            adpter.notifyDataSetChanged();
            tab_0.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_1.setTextColor(ContextCompat.getColor(this, R.color.font_flow_price));
            tab_2.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_0.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
            tab_1.setBackgroundResource(R.drawable.img_tab);
            tab_2.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
        }
    }

    private void onClickTabThree() {
        if (childList == null)
            childList = new ArrayList<>();
        childList.clear();
        for (PackageInfo entity : groupList) {
            if (!CommonUtil.isNull(entity.getDegreeCode()) && entity.getDegreeCode().equals("2")) {
                tv_no_package.setVisibility(View.GONE);
                childList.add(entity);
            } else { //添加没有流量包提醒
                if (Constants.PACKAGE_TWO_YEAR.equals(entity.getDegreeCode()))
                    tv_no_package.setVisibility(View.VISIBLE);
            }
        }
        if (childList != null && childList.size() > 0) {
            adpter.setDegreeCode("2");
            adpter.setSelectPackInfo(childList.get(0));
            adpter.setPosition(0);
            adpter.setSelectPosition(0);
            adpter.notifyDataSetChanged();
            tab_0.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_1.setTextColor(ContextCompat.getColor(this, R.color.vin_register_hint));
            tab_2.setTextColor(ContextCompat.getColor(this, R.color.font_flow_price));
            tab_0.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
            tab_1.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
            tab_2.setBackgroundResource(R.drawable.img_tab);
        }
    }

    @Override
    public void onEBDataCallBack(int p) {
        if (childList != null && childList.size() > 0) {
            PackageInfo packageInfo = childList.get(p);
            if (packageInfo != null) {
                package_name.setText(packageInfo.getPackageName());
                start_date.setText(packageInfo.getStartDate().substring(0, 10));
                end_date.setText(packageInfo.getEndDate().substring(0, 10));
                package_price.setText("" + packageInfo.getPackagePrice());
                offer_desc.setText(packageInfo.getOfferDesc() + "");
                actual_price.setText("" + packageInfo.getActualPrice());
                description.setText(packageInfo.getDescription());
                isShowActualPrice(p);
                isEBPackage = "1".equals(packageInfo.getIsEBPackage());
                package_name_eb.setVisibility(isEBPackage ? View.VISIBLE : View.GONE);
                eb_layout_rule.setVisibility(isEBPackage ? View.VISIBLE : View.GONE);
            }
        }
    }

    private void isShowActualPrice(int position) {
        if (childList != null && childList.get(position) != null && childList.get(position).getPackagePrice() != childList.get(position).getActualPrice()) {
            package_layout.setVisibility(View.VISIBLE);
            package_price.setVisibility(View.VISIBLE);
        } else {
            package_layout.setVisibility(View.INVISIBLE);
            package_price.setVisibility(View.INVISIBLE);
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        top_layout = null;
        if (packagePresenter != null) {
            packagePresenter.finish();
            packagePresenter = null;
        }
    }
}